package com.bt.lms.dao.servise.impl;

import com.bt.lms.entity.Role;
import com.bt.lms.entity.page.Page;
import com.bt.lms.dao.servise.RoleDao;
import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色服务dao实现
 *
 * @author 徐大永
 */
public class RoleDaoImpl implements RoleDao {

    @Override
    public int insert(String roleSql, Role role) {

        //要入库的属性
        String code = role.getCode();
        String name = role.getName();
        String details = role.getDetails();
        String builder = role.getBuilder();
        LocalDateTime buildTime = role.getBuildTime();
        String buildTImeStr = buildTime.toString();
        Integer status = role.getStatus();
        try {
            //1.连接
            Connection connection = UserDaoImpl.pond();
            //2.获取域处理对象
            PreparedStatement preparedStatement = connection.prepareStatement(roleSql);
            //2.2 处理SQL语句
            preparedStatement.setString(1, code);
            preparedStatement.setString(2, name);
            preparedStatement.setString(3, details);
            preparedStatement.setString(4, builder);
            preparedStatement.setString(5, buildTImeStr);
            preparedStatement.setInt(6, status);
            //3.执行SQL
            int i = preparedStatement.executeUpdate();
            //4.关闭资源
            preparedStatement.close();
            connection.close();

            return i;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int inserts(String sql, List<Long> roleIds, Long userId) {

        //要写入的数据
        LocalDateTime installRoleTime = LocalDateTime.now();
        String installRoleTimeStr = installRoleTime.toString();

        try {
            //连接
            Connection connection = UserDaoImpl.pond();
            //域处理
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            for (Long roleId:roleIds){
                preparedStatement.setLong(1, userId);
                preparedStatement.setLong(2, roleId);
                preparedStatement.setString(3, installRoleTimeStr);
                preparedStatement.addBatch();
            }
            //执行
            int[] ints = preparedStatement.executeBatch();
            //资源关闭
            preparedStatement.close();
            connection.close();
            return ints.length;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(String sql, Role role) {

        //需要用到的属性
        Long id = role.getId();
        String name = role.getName();
        String details = role.getDetails();

        try {
            //获取连接
            Connection connection = UserDaoImpl.pond();
            //域处理
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, name);
            preparedStatement.setString(2, details);
            preparedStatement.setLong(3, id);
            //执行
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int update(String sql, Long id) {

        try {
            //连接
            Connection connection = UserDaoImpl.pond();
            //域处理
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setLong(1, id);
            //执行
            int i = preparedStatement.executeUpdate();
            //关闭
            preparedStatement.close();
            connection.close();
            return i;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int update(String sql, Long userId, Long roleId) {

        try {
            //连接
            Connection connection = UserDaoImpl.pond();
            //域处理
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setLong(1, userId);
            preparedStatement.setLong(2, roleId);
            //执行
            int i = preparedStatement.executeUpdate();
            //取消连接
            preparedStatement.close();
            connection.close();
            return i;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Page<Role> select(String sql, Page<Role> page, String roleSum) {

        //需要维护的数据
        List<Role> roles = new ArrayList<>();
        page.setRecords(roles);

        //查询用数据
        Integer size = page.getSize();
        Integer current = page.getCurrent();
        int front = size * (current - 1);

        //连接
        Connection connection = UserDaoImpl.pond();
        try {
            //域处理
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, front);
            preparedStatement.setInt(2, size);

            //执行（总数）
            ResultSet sumRS = preparedStatement.executeQuery(roleSum);
            sumRS.next();
            long sum = sumRS.getLong(1);
            page.setTotal(sum);

            //执行（角色具体信息）
            ResultSet roleRS = preparedStatement.executeQuery();
            while (roleRS.next()) {

                Role role = new Role();
                //编码、名称、创建人、创建时间、最近登录时间
                long id = roleRS.getLong("id");
                String code = roleRS.getString("code");
                String name = roleRS.getString("name");
                String details = roleRS.getString("details");
                String builder = roleRS.getString("builder");
                String builderTimeStr = roleRS.getString("builder_time");
                String alterTimeStr = roleRS.getString("alter_time");

                //带走
                role.setId(id);
                role.setCode(code);
                role.setName(name);
                role.setDetails(details);
                role.setBuilder(builder);
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime builderTime = LocalDateTime.parse(builderTimeStr, dateTimeFormatter);
                role.setBuildTime(builderTime);
                if (alterTimeStr != null) {
                    role.setAlterTime(LocalDateTime.parse(alterTimeStr, dateTimeFormatter));
                } else
                    role.setAlterTime(null);

                roles.add(role);

            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


        return page;
    }

    @Override
    public List<Long> select(String sql, Long userId) {

        //要返回的对象
        List<Long> roleIds = new ArrayList<>();

        try {
            //连接
            Connection connection = UserDaoImpl.pond();
            //预编译
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setLong(1,userId);
            //执行
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                long roleId = resultSet.getLong(1);
                roleIds.add(roleId);
            }
            //关闭资源
            preparedStatement.close();
            connection.close();

            return roleIds;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Page<Role> selectCor(String sql, Page<Role> page, String roleSum) {
        //需要维护的数据
        List<Role> roles = new ArrayList<>();
        page.setRecords(roles);

        //查询用数据
        Integer size = page.getSize();
        Integer current = page.getCurrent();
        int front = size * (current - 1);

        //连接
        Connection connection = UserDaoImpl.pond();
        try {
            //域处理
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, front);
            preparedStatement.setInt(2, size);

            //执行（总数）
            ResultSet sumRS = preparedStatement.executeQuery(roleSum);
            sumRS.next();
            long sum = sumRS.getLong(1);
            page.setTotal(sum);

            //执行（角色具体信息）
            ResultSet roleRS = preparedStatement.executeQuery();
            while (roleRS.next()) {

                Role role = new Role();
                //id、编码、名称、创建人
                long id = roleRS.getLong("id");
                String code = roleRS.getString("code");
                String name = roleRS.getString("name");
                String details = roleRS.getString("details");

                //带走
                role.setId(id);
                role.setCode(code);
                role.setName(name);
                role.setDetails(details);
                roles.add(role);

            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


        return page;
    }
}
